from django.contrib import admin
from .models import Community, Owner, Maintenance, Announcement, SystemSetting

# 小区信息管理
@admin.register(Community)
class CommunityAdmin(admin.ModelAdmin):
    list_display = ('name', 'address', 'building_count', 'unit_count', 'house_count', 'parking_count')
    search_fields = ('name', 'address')
    ordering = ('name',)

# 业主信息管理
@admin.register(Owner)
class OwnerAdmin(admin.ModelAdmin):
    list_display = ('name', 'community', 'building', 'unit', 'room_number', 'phone', 'is_active')
    search_fields = ('name', 'phone', 'id_card', 'room_number')
    list_filter = ('community', 'is_active')
    raw_id_fields = ('community',)
    ordering = ('community', 'building', 'unit', 'room_number')

# 报修记录管理
@admin.register(Maintenance)
class MaintenanceAdmin(admin.ModelAdmin):
    list_display = ('id', 'owner', 'type', 'status', 'report_time', 'handler')
    search_fields = ('owner__name', 'content')
    list_filter = ('status', 'type', 'report_time')
    raw_id_fields = ('owner', 'handler')
    date_hierarchy = 'report_time'
    ordering = ('-report_time',)
    
    # 自定义状态变更操作
    actions = ['mark_as_processing', 'mark_as_completed', 'mark_as_rejected']
    
    def mark_as_processing(self, request, queryset):
        queryset.update(status='processing', handler=request.user)
    mark_as_processing.short_description = '标记为处理中'
    
    def mark_as_completed(self, request, queryset):
        queryset.update(status='completed')
    mark_as_completed.short_description = '标记为已完成'
    
    def mark_as_rejected(self, request, queryset):
        queryset.update(status='rejected')
    mark_as_rejected.short_description = '标记为已拒绝'

# 公告管理
@admin.register(Announcement)
class AnnouncementAdmin(admin.ModelAdmin):
    list_display = ('title', 'type', 'publisher', 'publish_date', 'expire_date', 'is_sticky', 'views_count')
    search_fields = ('title', 'content')
    list_filter = ('type', 'is_sticky', 'publish_date')
    raw_id_fields = ('publisher',)
    date_hierarchy = 'publish_date'
    ordering = ('-is_sticky', '-publish_date')

# 系统设置管理
@admin.register(SystemSetting)
class SystemSettingAdmin(admin.ModelAdmin):
    list_display = ('company_name', 'system_name', 'updated_at', 'updated_by')
    readonly_fields = ('updated_at', 'updated_by')
    
    # 确保只有一个系统设置实例
    def has_add_permission(self, request):
        # 如果已经存在系统设置，则不允许添加新的
        return SystemSetting.objects.count() == 0
    
    # 保存时自动设置更新人和更新时间
    def save_model(self, request, obj, form, change):
        obj.updated_by = request.user
        super().save_model(request, obj, form, change)
